package com.example.remotecontrol.ui.remote

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AcUnit
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Air
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.BedtimeOff
import androidx.compose.material.icons.filled.Eco
import androidx.compose.material.icons.filled.Power
import androidx.compose.material.icons.filled.Remove
import androidx.compose.material.icons.filled.SwapVert
import androidx.compose.material.icons.filled.WaterDrop
import androidx.compose.material.icons.filled.Waves
import androidx.compose.material.icons.filled.Whatshot
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Snackbar
import androidx.compose.material3.Surface
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.remotecontrol.data.model.DeviceType

/**
 * 空调遥控器界面
 */
@Composable
fun ACRemoteScreen(
    viewModel: RemoteViewModel = hiltViewModel()
) {
    val selectedDevice by viewModel.selectedDevice.collectAsState()
    val irAvailable by viewModel.irAvailable.collectAsState()
    val commandStatus by viewModel.commandStatus.collectAsState()
    
    // 空调状态
    var isACOn by remember { mutableStateOf(false) }
    var currentTemp by remember { mutableIntStateOf(25) }
    var currentMode by remember { mutableStateOf(ACMode.COOL) }
    var fanSpeed by remember { mutableStateOf(FanSpeed.AUTO) }
    var isSwingOn by remember { mutableStateOf(false) }
    var isTurboOn by remember { mutableStateOf(false) }
    var isSleepOn by remember { mutableStateOf(false) }
    var isEcoOn by remember { mutableStateOf(false) }
    
    Surface(
        modifier = Modifier.fillMaxSize(),
        color = MaterialTheme.colorScheme.background
    ) {
        Column(
            modifier = Modifier
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            // 设备名称
            Text(
                text = selectedDevice?.name ?: "空调遥控器",
                style = MaterialTheme.typography.titleLarge,
                textAlign = TextAlign.Center
            )
            
            if (!irAvailable) {
                Spacer(modifier = Modifier.height(8.dp))
                Text(
                    text = "您的设备不支持红外功能",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.error,
                    textAlign = TextAlign.Center
                )
            }
            
            Spacer(modifier = Modifier.height(24.dp))
            
            // 主控制界面
            Card(
                modifier = Modifier.fillMaxWidth(),
                elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
                shape = RoundedCornerShape(16.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(16.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    // 电源开关
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = if (isACOn) "开启" else "关闭",
                            style = MaterialTheme.typography.titleMedium
                        )
                        
                        ACButton(
                            icon = Icons.Default.Power,
                            tint = if (isACOn) Color(0xFF4CAF50) else MaterialTheme.colorScheme.primary,
                            background = if (isACOn) 
                                MaterialTheme.colorScheme.primaryContainer 
                            else 
                                MaterialTheme.colorScheme.surfaceVariant,
                            onClick = {
                                isACOn = !isACOn
                                viewModel.sendIRCommand("POWER")
                            },
                            enabled = irAvailable
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(24.dp))
                    
                    // 温度显示和控制
                    Card(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 8.dp),
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.primaryContainer
                        ),
                        shape = RoundedCornerShape(12.dp)
                    ) {
                        Column(
                            modifier = Modifier.padding(16.dp),
                            horizontalAlignment = Alignment.CenterHorizontally
                        ) {
                            Text(
                                text = "温度设置",
                                style = MaterialTheme.typography.titleMedium
                            )
                            
                            Spacer(modifier = Modifier.height(16.dp))
                            
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.Center
                            ) {
                                // 减温按钮
                                ACButton(
                                    icon = Icons.Default.Remove,
                                    onClick = {
                                        if (currentTemp > 16) {
                                            currentTemp--
                                            viewModel.sendIRCommand("TEMP_DOWN")
                                        }
                                    },
                                    enabled = irAvailable && isACOn && currentTemp > 16,
                                    modifier = Modifier.size(56.dp)
                                )
                                
                                Spacer(modifier = Modifier.width(16.dp))
                                
                                // 温度显示
                                Box(
                                    modifier = Modifier
                                        .size(100.dp)
                                        .clip(CircleShape)
                                        .background(
                                            when (currentMode) {
                                                ACMode.COOL -> Color(0xFF2196F3).copy(alpha = 0.2f)
                                                ACMode.HEAT -> Color(0xFFFF9800).copy(alpha = 0.2f)
                                                ACMode.DRY -> Color(0xFF03A9F4).copy(alpha = 0.2f)
                                                ACMode.FAN -> Color(0xFF9E9E9E).copy(alpha = 0.2f)
                                                ACMode.AUTO -> Color(0xFF4CAF50).copy(alpha = 0.2f)
                                            }
                                        )
                                        .border(
                                            width = 2.dp,
                                            color = when (currentMode) {
                                                ACMode.COOL -> Color(0xFF2196F3)
                                                ACMode.HEAT -> Color(0xFFFF9800)
                                                ACMode.DRY -> Color(0xFF03A9F4)
                                                ACMode.FAN -> Color(0xFF9E9E9E)
                                                ACMode.AUTO -> Color(0xFF4CAF50)
                                            },
                                            shape = CircleShape
                                        ),
                                    contentAlignment = Alignment.Center
                                ) {
                                    Column(
                                        horizontalAlignment = Alignment.CenterHorizontally
                                    ) {
                                        Text(
                                            text = "$currentTemp°C",
                                            style = MaterialTheme.typography.headlineMedium,
                                            fontWeight = FontWeight.Bold
                                        )
                                        
                                        val modeText = when(currentMode) {
                                            ACMode.COOL -> "制冷"
                                            ACMode.HEAT -> "制热"
                                            ACMode.DRY -> "除湿"
                                            ACMode.FAN -> "送风"
                                            ACMode.AUTO -> "自动"
                                        }
                                        Text(
                                            text = modeText,
                                            style = MaterialTheme.typography.bodySmall
                                        )
                                    }
                                }
                                
                                Spacer(modifier = Modifier.width(16.dp))
                                
                                // 加温按钮
                                ACButton(
                                    icon = Icons.Default.Add,
                                    onClick = {
                                        if (currentTemp < 30) {
                                            currentTemp++
                                            viewModel.sendIRCommand("TEMP_UP")
                                        }
                                    },
                                    enabled = irAvailable && isACOn && currentTemp < 30,
                                    modifier = Modifier.size(56.dp)
                                )
                            }
                        }
                    }
                    
                    Spacer(modifier = Modifier.height(24.dp))
                    
                    // 模式选择
                    Text(
                        text = "模式",
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.align(Alignment.Start)
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        ACModeButton(
                            icon = Icons.Default.AcUnit,
                            text = "制冷",
                            isSelected = currentMode == ACMode.COOL,
                            onClick = {
                                currentMode = ACMode.COOL
                                viewModel.sendIRCommand("MODE_COOL")
                            },
                            enabled = irAvailable && isACOn
                        )
                        
                        ACModeButton(
                            icon = Icons.Default.Whatshot,
                            text = "制热",
                            isSelected = currentMode == ACMode.HEAT,
                            onClick = {
                                currentMode = ACMode.HEAT
                                viewModel.sendIRCommand("MODE_HEAT")
                            },
                            enabled = irAvailable && isACOn
                        )
                        
                        ACModeButton(
                            icon = Icons.Default.WaterDrop,
                            text = "除湿",
                            isSelected = currentMode == ACMode.DRY,
                            onClick = {
                                currentMode = ACMode.DRY
                                viewModel.sendIRCommand("MODE_DRY")
                            },
                            enabled = irAvailable && isACOn
                        )
                        
                        ACModeButton(
                            icon = Icons.Default.Air,
                            text = "送风",
                            isSelected = currentMode == ACMode.FAN,
                            onClick = {
                                currentMode = ACMode.FAN
                                viewModel.sendIRCommand("MODE_FAN")
                            },
                            enabled = irAvailable && isACOn
                        )
                        
                        ACModeButton(
                            icon = Icons.Default.SwapVert,
                            text = "自动",
                            isSelected = currentMode == ACMode.AUTO,
                            onClick = {
                                currentMode = ACMode.AUTO
                                viewModel.sendIRCommand("MODE_AUTO")
                            },
                            enabled = irAvailable && isACOn
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(24.dp))
                    
                    // 风速控制
                    Text(
                        text = "风速",
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.align(Alignment.Start)
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        FanSpeedButton(
                            text = "自动",
                            isSelected = fanSpeed == FanSpeed.AUTO,
                            onClick = {
                                fanSpeed = FanSpeed.AUTO
                                viewModel.sendIRCommand("FAN_AUTO")
                            },
                            enabled = irAvailable && isACOn
                        )
                        
                        FanSpeedButton(
                            text = "低风",
                            isSelected = fanSpeed == FanSpeed.LOW,
                            onClick = {
                                fanSpeed = FanSpeed.LOW
                                viewModel.sendIRCommand("FAN_LOW")
                            },
                            enabled = irAvailable && isACOn
                        )
                        
                        FanSpeedButton(
                            text = "中风",
                            isSelected = fanSpeed == FanSpeed.MEDIUM,
                            onClick = {
                                fanSpeed = FanSpeed.MEDIUM
                                viewModel.sendIRCommand("FAN_MID")
                            },
                            enabled = irAvailable && isACOn
                        )
                        
                        FanSpeedButton(
                            text = "高风",
                            isSelected = fanSpeed == FanSpeed.HIGH,
                            onClick = {
                                fanSpeed = FanSpeed.HIGH
                                viewModel.sendIRCommand("FAN_HIGH")
                            },
                            enabled = irAvailable && isACOn
                        )
                    }
                    
                    Spacer(modifier = Modifier.height(24.dp))
                    
                    // 功能开关
                    Text(
                        text = "功能",
                        style = MaterialTheme.typography.titleMedium,
                        modifier = Modifier.align(Alignment.Start)
                    )
                    
                    Spacer(modifier = Modifier.height(8.dp))
                    
                    FunctionSwitch(
                        text = "摆风",
                        icon = Icons.Default.Waves,
                        isChecked = isSwingOn,
                        onCheckedChange = {
                            isSwingOn = it
                            viewModel.sendIRCommand("SWING")
                        },
                        enabled = irAvailable && isACOn
                    )
                    
                    Divider(modifier = Modifier.padding(vertical = 8.dp))
                    
                    FunctionSwitch(
                        text = "强力",
                        icon = Icons.Default.ArrowDropDown,
                        isChecked = isTurboOn,
                        onCheckedChange = {
                            isTurboOn = it
                            viewModel.sendIRCommand("TURBO")
                        },
                        enabled = irAvailable && isACOn
                    )
                    
                    Divider(modifier = Modifier.padding(vertical = 8.dp))
                    
                    FunctionSwitch(
                        text = "睡眠",
                        icon = Icons.Default.BedtimeOff,
                        isChecked = isSleepOn,
                        onCheckedChange = {
                            isSleepOn = it
                            viewModel.sendIRCommand("SLEEP")
                        },
                        enabled = irAvailable && isACOn
                    )
                    
                    Divider(modifier = Modifier.padding(vertical = 8.dp))
                    
                    FunctionSwitch(
                        text = "节能",
                        icon = Icons.Default.Eco,
                        isChecked = isEcoOn,
                        onCheckedChange = {
                            isEcoOn = it
                            viewModel.sendIRCommand("ECO")
                        },
                        enabled = irAvailable && isACOn
                    )
                }
            }
            
            Spacer(modifier = Modifier.height(16.dp))
            
            // 操作状态提示
            if (commandStatus is CommandStatus.Error) {
                Snackbar {
                    Text(text = (commandStatus as CommandStatus.Error).message)
                }
            }
        }
    }
}

/**
 * 空调模式按钮
 */
@Composable
fun ACModeButton(
    icon: ImageVector,
    text: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    enabled: Boolean = true
) {
    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        modifier = Modifier
            .clip(RoundedCornerShape(8.dp))
            .clickable(enabled = enabled, onClick = onClick)
            .padding(8.dp)
    ) {
        Box(
            modifier = Modifier
                .size(48.dp)
                .clip(CircleShape)
                .background(
                    if (isSelected) MaterialTheme.colorScheme.primary
                    else MaterialTheme.colorScheme.surfaceVariant
                ),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                imageVector = icon,
                contentDescription = text,
                tint = if (isSelected) MaterialTheme.colorScheme.onPrimary
                      else MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(24.dp)
            )
        }
        
        Spacer(modifier = Modifier.height(4.dp))
        
        Text(
            text = text,
            style = MaterialTheme.typography.bodySmall,
            color = if (isSelected) MaterialTheme.colorScheme.primary
                   else MaterialTheme.colorScheme.onSurface
        )
    }
}

/**
 * 空调按钮
 */
@Composable
fun ACButton(
    icon: ImageVector,
    onClick: () -> Unit,
    modifier: Modifier = Modifier.size(48.dp),
    enabled: Boolean = true,
    tint: Color = MaterialTheme.colorScheme.primary,
    background: Color = MaterialTheme.colorScheme.surfaceVariant
) {
    Box(
        modifier = modifier
            .clip(CircleShape)
            .clickable(enabled = enabled, onClick = onClick)
            .background(background),
        contentAlignment = Alignment.Center
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null,
            tint = if (enabled) tint else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
        )
    }
}

/**
 * 风速按钮
 */
@Composable
fun FanSpeedButton(
    text: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    enabled: Boolean = true
) {
    Box(
        modifier = Modifier
            .clip(RoundedCornerShape(8.dp))
            .clickable(enabled = enabled, onClick = onClick)
            .background(
                if (isSelected) MaterialTheme.colorScheme.primaryContainer
                else MaterialTheme.colorScheme.surfaceVariant
            )
            .padding(vertical = 8.dp, horizontal = 16.dp),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = text,
            style = MaterialTheme.typography.bodyMedium,
            color = if (isSelected) MaterialTheme.colorScheme.primary
                   else MaterialTheme.colorScheme.onSurfaceVariant
        )
    }
}

/**
 * 功能开关
 */
@Composable
fun FunctionSwitch(
    text: String,
    icon: ImageVector,
    isChecked: Boolean,
    onCheckedChange: (Boolean) -> Unit,
    enabled: Boolean = true
) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        Row(
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = icon,
                contentDescription = null,
                tint = if (enabled) MaterialTheme.colorScheme.primary 
                      else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f),
                modifier = Modifier.size(24.dp)
            )
            
            Spacer(modifier = Modifier.width(16.dp))
            
            Text(
                text = text,
                style = MaterialTheme.typography.bodyLarge,
                color = if (enabled) MaterialTheme.colorScheme.onSurface
                      else MaterialTheme.colorScheme.onSurface.copy(alpha = 0.38f)
            )
        }
        
        Switch(
            checked = isChecked,
            onCheckedChange = onCheckedChange,
            enabled = enabled
        )
    }
}

/**
 * 空调模式
 */
enum class ACMode {
    COOL, HEAT, DRY, FAN, AUTO
}

/**
 * 风速等级
 */
enum class FanSpeed {
    AUTO, LOW, MEDIUM, HIGH
} 